import { ref, onUnmounted, watch } from "vue";
import Hls from "hls.js";
import { ElMessage } from "element-plus";
import * as Sentry from "@sentry/browser";

// 视频监控配置选项
interface VideoMonitorOptions {
  preloadExpireTime?: number; // 预加载缓存过期时间(ms)，默认5分钟
  maxPreloadCount?: number; // 最大预加载数量，默认10
  hlsConfig?: Hls.Config; // HLS配置
}

// 视频源信息
interface VideoSource {
  id: string; // 视频源唯一标识
  url: string; // 视频流URL
  thumbnailUrl?: string; // 缩略图URL
}

// 视频监控状态
interface VideoMonitorState {
  isLoading: boolean;
  loadProgress: number;
  isPlaying: boolean;
  currentQuality: string;
  bitrate: number;
  loadLatency: number;
  bufferTime: number;
}

export function useVideoMonitor(options: VideoMonitorOptions = {}) {
  // 配置参数
  const preloadExpireTime = options.preloadExpireTime || 5 * 60 * 1000;
  const maxPreloadCount = options.maxPreloadCount || 10;
  const hlsConfig = options.hlsConfig || {
    maxBufferLength: 30,
    maxMaxBufferLength: 60,
    startLevel: -1,
    maxBufferHole: 0.5,
    highLatencyMode: false
  };

  // 状态管理
  const videoElement = ref<HTMLVideoElement | null>(null);
  const hlsInstance = ref<Hls | null>(null);
  const videoSources = ref<Record<string, VideoSource>>({});
  const preloadCache = ref<Record<string, { timestamp: number }>>({});
  const preloadQueue = ref<string[]>([]);
  const currentSourceId = ref<string | null>(null);

  // 视频监控状态
  const state = ref<VideoMonitorState>({
    isLoading: false,
    loadProgress: 0,
    isPlaying: false,
    currentQuality: "自动",
    bitrate: 0,
    loadLatency: 0,
    bufferTime: 0
  });

  // 注册视频源
  const registerVideoSources = (sources: VideoSource[]) => {
    sources.forEach(source => {
      videoSources.value[source.id] = source;
    });
  };

  // 预加载视频
  const preloadVideo = async (sourceId: string) => {
    // 检查视频源是否存在
    const source = videoSources.value[sourceId];
    if (!source) {
      console.warn(`Video source ${sourceId} not found`);
      return false;
    }

    // 检查是否已缓存且未过期
    const cached = preloadCache.value[sourceId];
    if (cached && Date.now() - cached.timestamp < preloadExpireTime) {
      return true;
    }

    try {
      const start = performance.now();

      // 只请求HLS索引文件，不加载实际视频内容
      const response = await fetch(source.url, {
        method: "HEAD",
        cache: "force-cache"
      });

      if (response.ok) {
        // 更新缓存
        preloadCache.value[sourceId] = { timestamp: Date.now() };

        // 维护预加载队列，超过最大数量则移除最早的
        if (!preloadQueue.value.includes(sourceId)) {
          preloadQueue.value.push(sourceId);
          if (preloadQueue.value.length > maxPreloadCount) {
            const oldest = preloadQueue.value.shift();
            if (oldest) delete preloadCache.value[oldest];
          }
        }

        // 记录性能指标
        const latency = Math.round(performance.now() - start);
        Sentry.addBreadcrumb({
          message: `Video preloaded: ${sourceId}`,
          category: "video",
          data: { sourceId, latency }
        });

        return true;
      }
    } catch (error) {
      console.error(`Preload video ${sourceId} failed:`, error);
      Sentry.captureException(error);
    }

    return false;
  };

  // 预加载多个视频
  const preloadVideos = async (sourceIds: string[]) => {
    // 限制并发请求数量为3，避免网络拥堵
    const concurrency = 3;
    const batches = [];

    for (let i = 0; i < sourceIds.length; i += concurrency) {
      batches.push(sourceIds.slice(i, i + concurrency));
    }

    for (const batch of batches) {
      await Promise.all(batch.map(id => preloadVideo(id)));
    }
  };

  // 设置视频元素
  const setVideoElement = (el: HTMLVideoElement | null) => {
    // 清理之前的实例
    if (videoElement.value && videoElement.value !== el) {
      stopVideo();
    }

    videoElement.value = el;
  };

  // 播放视频
  const playVideo = async (sourceId: string) => {
    if (!videoElement.value) {
      ElMessage.error("未找到视频播放器元素");
      return false;
    }

    // 停止当前播放的视频
    if (currentSourceId.value) {
      stopVideo();
    }

    // 检查视频源
    const source = videoSources.value[sourceId];
    if (!source) {
      ElMessage.error(`视频源 ${sourceId} 不存在`);
      return false;
    }

    // 更新状态
    currentSourceId.value = sourceId;
    state.value.isLoading = true;
    state.value.loadProgress = 0;
    state.value.loadLatency = 0;
    state.value.bufferTime = 0;

    try {
      const startLoadTime = performance.now();

      // 设置缩略图
      if (source.thumbnailUrl) {
        videoElement.value.poster = source.thumbnailUrl;
      }

      // 初始化HLS
      if (Hls.isSupported()) {
        // 创建HLS实例，添加进度监控
        const hlsConfigWithProgress = {
          ...hlsConfig,
          loader: {
            ...hlsConfig.loader,
            onProgress: (progress: number) => {
              state.value.loadProgress = Math.round(progress * 100);
            }
          }
        };

        hlsInstance.value = new Hls(hlsConfigWithProgress);

        // 监听HLS事件
        hlsInstance.value.on(Hls.Events.MANIFEST_PARSED, () => {
          // 计算加载延迟
          state.value.loadLatency = Math.round(
            performance.now() - startLoadTime
          );
          state.value.isLoading = false;

          // 自动播放
          videoElement.value
            ?.play()
            .then(() => {
              state.value.isPlaying = true;
            })
            .catch(err => {
              console.error("Auto-play failed:", err);
              state.value.isPlaying = false;
            });

          // 记录性能指标
          Sentry.addBreadcrumb({
            message: `Video started: ${sourceId}`,
            category: "video",
            data: {
              sourceId,
              latency: state.value.loadLatency
            }
          });
        });

        hlsInstance.value.on(Hls.Events.BUFFER_CREATED, (event, data) => {
          if (data.type === "video") {
            state.value.bufferTime = Math.round(
              performance.now() - startLoadTime
            );
          }
        });

        hlsInstance.value.on(Hls.Events.LEVEL_SWITCHED, (event, data) => {
          state.value.currentQuality = ["低", "中", "高"][data.level] || "自动";
          state.value.bitrate = data.details.bitrate / 1000;
        });

        hlsInstance.value.on(Hls.Events.ERROR, (event, data) => {
          console.error("HLS error:", data);
          Sentry.captureException(
            new Error(`HLS error: ${data.type} - ${data.details}`)
          );

          // 尝试恢复
          if (data.fatal) {
            switch (data.type) {
              case Hls.ErrorTypes.NETWORK_ERROR:
                hlsInstance.value?.startLoad();
                break;
              case Hls.ErrorTypes.MEDIA_ERROR:
                hlsInstance.value?.recoverMediaError();
                break;
              default:
                // 无法恢复的错误，重新加载
                stopVideo();
                playVideo(sourceId);
                break;
            }
          }
        });

        // 加载视频源
        hlsInstance.value.loadSource(source.url);
        hlsInstance.value.attachMedia(videoElement.value);
      }
      // Safari直接支持HLS
      else if (
        videoElement.value.canPlayType("application/vnd.apple.mpegurl")
      ) {
        videoElement.value.src = source.url;

        videoElement.value.addEventListener("loadedmetadata", () => {
          state.value.loadLatency = Math.round(
            performance.now() - startLoadTime
          );
          state.value.isLoading = false;

          videoElement.value?.play().then(() => {
            state.value.isPlaying = true;
          });
        });

        videoElement.value.addEventListener("progress", () => {
          if (videoElement.value?.buffered.length) {
            const bufferedEnd = videoElement.value.buffered.end(
              videoElement.value.buffered.length - 1
            );
            const duration = videoElement.value.duration;
            if (duration > 0) {
              state.value.loadProgress = Math.round(
                (bufferedEnd / duration) * 100
              );
            }
          }
        });
      }

      return true;
    } catch (error) {
      console.error(`Play video ${sourceId} failed:`, error);
      Sentry.captureException(error);

      state.value.isLoading = false;
      ElMessage.error("视频加载失败，请重试");
      return false;
    }
  };

  // 停止视频播放
  const stopVideo = () => {
    if (videoElement.value) {
      videoElement.value.pause();
      videoElement.value.src = "";
      videoElement.value.poster = "";
    }

    if (hlsInstance.value) {
      hlsInstance.value.destroy();
      hlsInstance.value = null;
    }

    state.value = {
      isLoading: false,
      loadProgress: 0,
      isPlaying: false,
      currentQuality: "自动",
      bitrate: 0,
      loadLatency: 0,
      bufferTime: 0
    };

    currentSourceId.value = null;
  };

  // 切换视频清晰度
  const switchQuality = () => {
    if (!hlsInstance.value || !currentSourceId.value) return;

    const currentLevel = hlsInstance.value.currentLevel;
    const levels = hlsInstance.value.levels;

    if (!levels || levels.length <= 1) return;

    // 循环切换清晰度
    const nextLevel = currentLevel < levels.length - 1 ? currentLevel + 1 : 0;
    hlsInstance.value.startLevel = nextLevel;
    hlsInstance.value.loadLevel = nextLevel;
  };

  // 清理资源
  onUnmounted(() => {
    stopVideo();
  });

  // 监听视频元素的播放状态
  watch(videoElement, (newEl, oldEl) => {
    if (oldEl) {
      oldEl.removeEventListener("play", handlePlay);
      oldEl.removeEventListener("pause", handlePause);
    }

    if (newEl) {
      newEl.addEventListener("play", handlePlay);
      newEl.addEventListener("pause", handlePause);
    }
  });

  // 处理播放事件
  const handlePlay = () => {
    state.value.isPlaying = true;
  };

  // 处理暂停事件
  const handlePause = () => {
    state.value.isPlaying = false;
  };

  return {
    state,
    registerVideoSources,
    preloadVideo,
    preloadVideos,
    setVideoElement,
    playVideo,
    stopVideo,
    switchQuality,
    currentSourceId
  };
}
